//
// Created by wangjunjun on 2023/10/26.
//
#include <iostream>
#include <memory>
#include <vector>
#include <thread>
#include <mutex>
#include "AbstractFactory.h"
#include "ConcreteFactoryA.h"
#include "ConcreteFactoryB.h"
std::mutex mtx;  // 互斥锁，用于保护共享资源的访问

void createAndPerformAction(std::shared_ptr<AbstractFactory> factory) {
    std::shared_ptr<AbstractProduct> product = factory->createProduct();

    // 使用互斥锁保护共享资源的访问
    std::lock_guard<std::mutex> lock(mtx);
    product->performAction();
}

int main() {
    std::vector<std::thread> threads;
    const int numThreads = 10;

    // 创建并发线程
    for (int i = 0; i < numThreads; ++i) {
        threads.emplace_back([&]() {
            // 使用 ConcreteFactoryA 创建产品
            std::shared_ptr<AbstractFactory> factoryA = std::make_shared<ConcreteFactoryA>();
            createAndPerformAction(factoryA);

            // 使用 ConcreteFactoryB 创建产品
            std::shared_ptr<AbstractFactory> factoryB = std::make_shared<ConcreteFactoryB>();
            createAndPerformAction(factoryB);
        });
    }

    // 等待所有线程完成
    for (auto& thread : threads) {
        thread.join();
    }
    return 0;
}